package middleware

import (
	"cabinet/pkg/log"
	"cabinet/serializer"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"net/http"
	"runtime/debug"
)

func Exception(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			err := errors.Errorf("%v", err)
			log.Log().Error("runtime exception, stack: %s", string(debug.Stack()))
			res := serializer.Response{
				Code: serializer.InternalServerError,
				Data: map[string]interface{}{},
				Msg:  serializer.CustomError[serializer.InternalServerError],
			}
			// 生产环境隐藏底层报错
			if err != nil && gin.Mode() != gin.ReleaseMode {
				res.Error = err.Error()
			}
			// set json data
			c.JSON(http.StatusOK, res)
			c.Abort()
			return
		}
	}()
	c.Next()
}
